package com.csit.dao.impl;

import java.util.Date;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.csit.bean.Pager;
import com.csit.dao.SaleDao;
import com.csit.entity.DataDictionary;
import com.csit.entity.Sale;
import com.csit.util.StringUtil;

@Repository
public class SaleDaoImpl extends BaseDaoImpl<Sale, Integer> implements SaleDao {
	
	public Long getCount(DataDictionary shop) {
		Assert.notNull(shop, "Shop is required");
		String hql = "select count(*) from Sale where shop=:shop and createDate=:createDate";
		Query query = getSession().createQuery(hql);
		query.setEntity("shop", shop);
		query.setDate("createDate", new Date());
		Long count = (Long) query.uniqueResult();
		return count==null?0L:count;
	}

	public Pager querySale(Pager pager, Sale sale, Date beginDate, Date endDate) {
		Criteria criteria = getSession().createCriteria(Sale.class);
		
		criteria.createAlias("shop", "shop", CriteriaSpecification.LEFT_JOIN);
		criteria.createAlias("storeHouse", "storeHouse", CriteriaSpecification.LEFT_JOIN);
		criteria.createAlias("customer", "customer", CriteriaSpecification.LEFT_JOIN);
		
		criteria.add(Restrictions.eq("shop", sale.getShop()));
		
		if(StringUtil.isNotNull(sale.getSaleCode())){
			criteria.add(Restrictions.like("saleCode", sale.getSaleCode(), MatchMode.ANYWHERE));
		}
		
		if(sale.getCustomer()!=null){
			criteria.add(Restrictions.eq("customer", sale.getCustomer()));
		}
		if(beginDate!=null){
			criteria.add(Restrictions.ge("saleDate", beginDate));
		}
		if(endDate!=null){
			criteria.add(Restrictions.le("saleDate", endDate));
		}
		Long totalCount = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();

		criteria.setProjection(null);
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		criteria.setFirstResult(pager.getBeginCount());
		criteria.setMaxResults(pager.getPageSize());
		criteria.addOrder(Order.desc("saleCode"));
		pager.setTotalCount(totalCount);
		pager.setList(criteria.list());
		return pager;
	}
}
